//
//  WelcomeUserViewController.swift
//  weibo19
//
//  Created by Arvin on 15/11/12.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

class WelcomeUserViewController: UIViewController {

    override func loadView() {
        view = backImage
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addSubUI()
        iconImage.sd_setImageWithURL(UserAccountViewModel().iconURL, placeholderImage: UIImage(named: "avatar_default_big"))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // 约束控件的动画, 要在这个方法中实现(viewDidAppear), 控件进行了约束, 就不要手动设置控件的frame, 如果手动设置frame, 就会导致系统计算控件约束值失误
    override func viewDidAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 更新控件约束
        iconImage.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom).offset(-view.bounds.height + 200)
        }
        // 动画
        UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 9.8, options: [], animations: { () -> Void in
            self.view.layoutIfNeeded()
            }) { (isover) -> Void in
                
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.nameLabel.alpha = 1.0
                    }, completion: { (finished) -> Void in
                            // 跳转控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(switchController, object: nil)
                })
        }
    }
    
    // MARK: 懒加载控件
    private lazy var backImage: UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    private lazy var iconImage: UIImageView = {
        let icon = UIImageView()
        icon.layer.cornerRadius = 45
        icon.layer.masksToBounds = true
        return icon
    }()
    private lazy var nameLabel: UILabel = {
        let name = UILabel()
        name.textAlignment = NSTextAlignment.Center
        name.font = UIFont.systemFontOfSize(15)
        name.sizeToFit()
        name.alpha = 0;
        name.text = UserAccount.loadAccount()?.name ?? "欢迎登录..."
        return name
    }()
    // MARK: 添加控件
    private func addSubUI() {
        view.addSubview(iconImage)
        view.addSubview(nameLabel)

        // 约束
        iconImage.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom).offset(-180)
            make.centerX.equalTo(self.view.snp_centerX)
            make.width.equalTo(90)
            make.height.equalTo(90)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(iconImage.snp_bottom).offset(16)
            make.centerX.equalTo(iconImage.snp_centerX)
        }
    }
}
